//
//  TimerButton.swift
//  Exchange
//
//  Created by rui on 2018/4/19.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

enum TimerButtonState {
    case normal
    case active
    case end
    case enabled
}

class TimerButton: UIButton {

    var timeInterval: Int = 60
    
    private var count: Int = 0
    
    private var timer: Timer?
    
    var timerState: TimerButtonState = .normal {
        didSet {
            switch timerState {
            case .normal:
                self.setTitle(kText("获取验证码"), for: .normal)
                self.setTitleColor(kThemeColor, for: .normal)
                self.isEnabled = true
                timerEnd()
            case .active:
                self.isEnabled = false
                self.setTitleColor(kThemeColor, for: .normal)
                timerStart()
            case .end:
                self.isEnabled = true
                self.setTitle(kText("重新获取验证码"), for: .normal)
                self.setTitleColor(kThemeColor, for: .normal)
                timerEnd()
            case .enabled:
                self.isEnabled = false
                self.setTitleColor(kPlaceholderColor, for: .normal)
                timerEnd()
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func timerStart() {
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerCount), userInfo: nil, repeats: true)
        }
        count = timeInterval
        timer?.fire()
    }
    
    func timerEnd() {
        timer?.invalidate()
        timer = nil
    }
    
    @objc func timerCount() {
        if count <= 0 {
            timerState = .end
        }else {
            count -= 1
            let str = String(format: kText("%lds后重新发送验证码") ,count)
            self.setTitle(str, for: .normal)
        }
    }
    
    deinit {
        timerEnd()
    }
}
